package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/models"
	"encoding/json"
	"github.com/astaxie/beego/orm"
	"golang.org/x/crypto/bcrypt"
	"strings"
)

type RegisterUserController struct {
	BaseController
}

func (this *RegisterUserController) Prepare() {
	this.BaseController.Prepare()
	this.checkAuthor("DataGrid")
}

func (this *RegisterUserController) Index() {
	this.Data["pageTitle"] = "注册用户"

	this.Data["canEdit"] = this.checkActionAuthor(this.controllerName, "Edit")
	this.Data["canDelete"] = this.checkActionAuthor(this.controllerName, "Delete")
	this.ActiveSidebarUrl()
	this.setTpl("register_user/index")
}

func (u *RegisterUserController) DataGrid() {
	var params models.UserQueryParam
	json.Unmarshal(u.Ctx.Input.RequestBody, &params)

	data, total := models.UserPageList(&params)

	u.BootstrapJson(total, data)
}

func (this *RegisterUserController) Edit() {
	if this.Ctx.Request.Method == "POST" {
		this.Save()
	}
	Id, _ := this.GetInt(":id", 0)
	m := &models.User{}
	var err error
	if Id > 0 {
		m, err = models.UserOne(Id)
		if err != nil {
			this.pageError("数据无效，请刷新后重试")
		}
	} else {
		m.Status = enums.Enabled
	}

	this.Data["m"] = m
	this.setTpl("register_user/edit", "shared/layout_pullbox", "footer")
}

func (this *RegisterUserController) Save() {
	m := models.User{}
	o := orm.NewOrm()
	var err error
	if err = this.ParseForm(&m); err != nil {
		this.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
	}
	if len(m.Password) > 0 {
		hash, err := bcrypt.GenerateFromPassword([]byte(strings.TrimSpace(m.Password)), bcrypt.DefaultCost)
		if err != nil {
			this.jsonResult(enums.JRCodeFailed, "生成密码失败", m.Id)
		}
		m.Password = string(hash)
	}
	//Id hidden input
	if m.Id == 0 {
		if _, err := o.Insert(&m); err != nil {
			this.jsonResult(enums.JRCodeFailed, "添加失败", m.Id)
		}
	} else {
		if oM, err := models.UserOne(m.Id); err != nil {
			this.jsonResult(enums.JRCodeFailed, "数据无效，请刷新后重试", m.Id)
		} else {
			m.Avatar = oM.Avatar
			if len(strings.TrimSpace(m.Password)) == 0 {
				m.Password = oM.Password
			}
		}
		if _, err := o.Update(&m); err != nil {
			this.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
		}
	}
	this.jsonResult(enums.JRCodeSuccess, "保存成功", m.Id)
}

func (this *RegisterUserController) Delete() {

}
